package com.czm.art_light.interceptor;

import com.czm.art_light.constant.CommonConsts;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashSet;

/**
 * 文件 拦截器
 */
@Component
@RequiredArgsConstructor
public class FileInterceptor implements HandlerInterceptor {
    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.bucket-name}")
    private String bucketName;

    @SuppressWarnings("NullableProblems")
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        // 获取请求的 URI
        String requestUri = request.getRequestURI();
        // 缓存10天
        response.setDateHeader(CommonConsts.CACHE_EXPIRES, System.currentTimeMillis() + 60 * 60 * 24 * 10 * 1000);
        //  http://192.18.23.23:9000/art-light/images/2024/12/24/0046fb16ee3b45e2ae7c7a3ae602a0ec.jpg
        String imageUrl = endpoint + CommonConsts.URL_PATH_PRE + bucketName + requestUri;
        URL url = new URL(imageUrl);
        try (
                OutputStream out = response.getOutputStream();
                InputStream input = url.openStream();
        ) {
            byte[] b = new byte[4096];
            for (int n; (n = input.read(b)) != -1; ) {
                out.write(b, 0, n);
            }
        }
        return false;
    }

}
